import 'package:enjoy_plus_ohos/pages/home/index.dart';
import 'package:enjoy_plus_ohos/pages/mine/index.dart';
import 'package:enjoy_plus_ohos/utils/eventBus.dart';
import 'package:enjoy_plus_ohos/utils/toast.dart';
import 'package:enjoy_plus_ohos/utils/token.dart';
import 'package:flutter/material.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 记录当前索引
  int currentIndex = 0;

  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "home",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png",
    },
    {
      "title": "my",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png",
    },
  ];

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
          icon: Image.asset(item['default'], width: 32, height: 32),
          activeIcon: Image.asset(item['active'], width: 32, height: 32),
          label: item['title'],
        ),
      );
    }
    return items;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    // 监听退出登录事件
    eventBus.on<LogoutEvent>().listen((event) {
      ToastUtil.showSuccess(event.message);
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex,
          children: [const HomePage(), MinePage(currentIndex: currentIndex)],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: barItemList(),
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }
}
